package com.sens.ipc.mybank.application;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.sens.ipc.mybank.Action;
import com.sens.ipc.mybank.hooker.Handle;
import com.sens.vo.MybankOrderVo;


public class Proxy {
    private Context context;
    private Callback callback;
    private BroadcastReceiver applicationReceiver;

    public Proxy(Context context, Callback callback) {
        this.context = context;
        if (callback == null) return;
        this.callback = callback;
        this.applicationReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent != null)
                    switch (intent.getAction()) {
                        case Action.Application.ACTION_NOTICE_MESSAGE:
                            Proxy.this.callback.noticeMessage(intent.getCharSequenceExtra(intent.getAction()));
                            break;
                        case Action.Application.ACTION_ADD_ORDER:
                            Proxy.this.callback.addOrder((MybankOrderVo) intent.getParcelableExtra(intent.getAction()));
                            break;
                        case Action.Application.ACTION_UPDATE_USERID:
                            Proxy.this.callback.updateUserId(intent.getStringExtra(intent.getAction()));
                            break;
                    }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Action.Application.ACTION_NOTICE_MESSAGE);
        intentFilter.addAction(Action.Application.ACTION_ADD_ORDER);
        intentFilter.addAction(Action.Application.ACTION_UPDATE_USERID);
        context.registerReceiver(applicationReceiver, intentFilter);
    }

    public Handle getHandle() {
        return new Handle(context) {
            @Override
            public void unBind() {
                if (applicationReceiver != null)
                    context.unregisterReceiver(applicationReceiver);
                context = null;
                callback = null;
                applicationReceiver = null;
            }
        };
    }
}
